package com.fhz.mvvmshopjava.ui.home;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.fhz.mvvmshopjava.R;
import com.fhz.mvvmshopjava.adapter.BannerAdapter;
import com.fhz.mvvmshopjava.core.BaseFragment;
import com.fhz.mvvmshopjava.databinding.HomeFragmentBinding;
import com.fhz.mvvmshopjava.entity.Banner;
import com.fhz.utilsfhz.ApiResponse;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.CircleIndicator;

import java.util.ArrayList;
import java.util.List;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class HomeFragment extends BaseFragment<HomeViewModel, HomeFragmentBinding> {

    @Override
    protected int getLayoutId() {
        return R.layout.home_fragment;
    }

    @Override
    protected void initData() {

        mBinding.rv.setLayoutManager(new LinearLayoutManager(getActivity()));

        List<Banner> bannerList  = new ArrayList<>();
        BannerAdapter bannerAdapter = new BannerAdapter(bannerList);
        mBinding.rv.setAdapter(bannerAdapter);


        //更新数据源
        mViewModel.getBanner().observe(getActivity(), new Observer<ApiResponse<List<Banner>>>() {
            @Override
            public void onChanged(ApiResponse<List<Banner>> listApiResponse) {
                bannerList.clear();
                bannerList.addAll(listApiResponse.getData());
                bannerAdapter.notifyDataSetChanged();

                mBinding.banner.setAdapter(new BannerImageAdapter<Banner>(listApiResponse.data) {
                    @Override
                    public void onBindView(BannerImageHolder holder, Banner data, int position, int size) {
                        //图片加载自己实现
                        Glide.with(holder.itemView)
                                .load(data.getImagepath())
                                .apply(RequestOptions.bitmapTransform(new RoundedCorners(30)))
                                .into(holder.imageView);
                    }
                })
                        .addBannerLifecycleObserver(HomeFragment.this)//添加生命周期观察者
                        .setIndicator(new CircleIndicator(getActivity()));
                //更多使用方法仔细阅读文档，或者查看demo

            }
        });

    }

    @Override
    protected HomeViewModel createViewModel() {
        return new ViewModelProvider(this).get(HomeViewModel.class);
    }
}